<?php

namespace App\Repository;
use App\Models\Promotion\SecSkill;
use App\Models\Promotion\SecSkillLog;

/**
 * 秒杀数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class SecKillRepository extends BaseRepository
{
    /**
     * 根据活动 Id 获取秒杀活动
     *
     * @param int $secKillId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getById(int $secKillId)
    {
        return SecSkill::query()->where('seckill_id', $secKillId)->first();
    }

    /**
     * 保存秒杀记录
     *
     * @param array $data
     * @return int|mixed
     */
    public function saveLog(array $data, int $logId = 0)
    {
        $query = $logId ? SecSkillLog::find($logId) : new SecSkillLog();
        foreach ($data as $field => $value) {
            $query->{$field} = $value;
        }
        return $query->save() ? $query->log_id : 0;
    }

    /**
     * 扣减商品库存
     *
     * @param int $productId
     * @param int $qty
     * @return int
     */
    public function reduceStock(int $productId, int $qty)
    {
        return SecSkill::query()
            ->where('product_id', $productId)
            ->where('stock_qty', '>=', $qty)
            ->decrement('stock_qty', $qty);
    }
}
